<template>
	<div class="FundList">
		<!-- 搜索条件 -->
		<transition name="el-zoom-in-top">
			<div class="sousuotiaojian">
				<el-form ref="form" label-position="left" class="dinghaishenz">
					<el-form-item label="产品搜索:">
						<div style="display: flex; align-items: center">
							<el-input
								v-model="form.fundLike"
								@input="form.fundLike = SpecialReplace(form.fundLike, true)"
								placeholder="请输入"
								size="medium"
								clearable
								:disabled="scrollLoading"
							></el-input>
							<el-button
								type="primary"
								icon="el-icon-search"
								size="small"
								style="margin-left: 30px"
								:loading="scrollLoading"
								:disabled="scrollLoading"
								@click=";(form.statusList = []), (form.fundRaiseType = ''), (form.fundType = ''), getFundNum(), getListItem()"
								>搜 索</el-button
							>
						</div>
					</el-form-item>
                    <div style="font-size:12px;color:#909399;margin-right:1px;">注：数据仅供内部参考，如对外报送请和产品开发部确认数据口径</div>
				</el-form>

				<div class="prodTypeClass">
					<el-button
						type="text"
						:disabled="scrollLoading"
						v-for="(item, index) in enumData.prodType"
						:key="index + 'a'"
						class="childrenya"
						@click="handleClick(item, 2)"
					>
						<span :style="item.fundRaiseType === form.fundRaiseType ? 'color:#409EFF;' : ''" class="fundTypeListClass">
							{{ item.fundTypeName }}（{{ item.fundTypeNumber }}）
						</span>
					</el-button>
				</div>
				<div class="fundTypeClass">
					<el-button
						type="text"
						class="fundTypeClassChidld"
						:disabled="scrollLoading"
						v-for="(item, index) in enumData.fundType"
						:key="index + 'b'"
						@click="handleClick(item, 1)"
					>
						<span class="fundTypeListClass" :style="item.fundTypeCode === form.fundType ? 'color:#409EFF;' : ''"
							>{{ item.fundTypeName }}（{{ item.fundTypeNumber }}）</span
						>
					</el-button>
				</div>
				<div class="prodTypeClass" style="margin-top: 2px">
					<el-button round :type="form.statusList.length === 0 ? `primary` : ''" :disabled="scrollLoading" @click="btnClick()"
						>全部</el-button
					>
					<el-button
						round
						:disabled="scrollLoading"
						v-for="item in fundOperationStatus"
						:type="form.statusList.includes(item.typeCode) ? `primary` : ''"
						:key="item.typeCode"
						@click="btnClick(item.typeCode)"
						>{{ item.typeName }}</el-button
					>
				</div>
			</div>
		</transition>

		<div class="listItemClass" :style="`height:${fundScrollData.length ? '' : '500px'};`">
			<template v-if="fundScrollData.length">
				<div
					class="fundListItemClass"
					@click="itemClick(item)"
					v-for="(item, index) in fundScrollData"
					:key="index"
					:style="index === 0 ? `border-top:none;` : ''"
				>
					<div class="itemName">
						<div>{{ item.fundFullName }}</div>
						<div class="itemFundType" v-if="item.fundType">{{ item.fundType }}</div>
						<div
							class="itemProdType"
							v-if="item.fundRaiseType"
							:style="item.fundRaiseType === '1' ? `background: #f5fee8; color: #62bb33` : `background: #fdeeee; color: #e96969`"
						>
							{{ item.fundRaiseType === '1' ? '公募' : '专户' }}
						</div>
					</div>
					<div class="itemName2">
						<div style="display: flex">
							<span class="itemFundCode">{{ item.fundCode }}</span>
							<el-divider direction="vertical"></el-divider>
							<span class="itemFundCode">
								<div class="hetongri">
									{{ item.fundRaiseType === '1' ? '合同生效日' : '产品成立日期' }}
								</div>
								<span>
									{{ item.establishDate | timerConversionStr }}
								</span>
							</span>
							<el-divider direction="vertical"></el-divider>
							<span class="itemFundCode">{{ item.statusMsg }}</span>
							<template
								v-if="
									item.fundRaiseType === '1' &&
									item.isSingleShare === '1' &&
									item.baseInfo &&
									item.baseInfo.branchShareList &&
									Array.isArray(item.baseInfo.branchShareList) &&
									item.baseInfo.branchShareList.length
								"
							>
								<el-divider direction="vertical"></el-divider>
								<span class="itemFundCode">有下属份额（{{ item.branchShareList ? item.branchShareList.length : 0 }}）</span>
							</template>
							<template v-if="item.fundRaiseType === '1' && item.isSingleShare !== '1'">
								<span class="itemFundCode"></span>
							</template>
						</div>
						<div class="dierhang">
							<div class="tuoguanhang"><span style="transform: scale(0.8)">托</span></div>
							<span>{{ item.trusteeFullName }}</span>
						</div>
					</div>
					<div class="itemName3">
						<div style="display: flex; align-items: center">
							<div style="width: 4%">
								<i class="el-icon-s-custom sub-el-icon" style="color: #8c95a8"></i>
							</div>
							<div style="width: 96%">
								<hintCom property="managerNames" :index="index" :item="item" style="font-size: 14px" />
							</div>
						</div>
						<div class="fileListClass">
							<div class="listxiahua" v-for="items in item.fileList" :key="items.id" @click.stop="downloadFileFunc()">
								<el-popover placement="bottom" trigger="hover" content="">
									<div class="xiazaitubiao">
										<div class="imgparnode" v-if="items.firstFileId" @click.stop="downloadFileFunc(items.firstFileId)">
											<div>
												<img src="../assets/icon_word@2x.png" alt="" />
											</div>
											<div>
												<span>Word版</span>
											</div>
										</div>
										<div class="imgparnode" v-if="items.finalFileId" @click.stop="downloadFileFunc(items.finalFileId)">
											<div>
												<img src="../assets/icon_pdf@2x.png" alt="" />
											</div>
											<div>
												<span>PDF版</span>
											</div>
										</div>
										<div class="imgparnode" v-if="items.sealedFileId" @click.stop="downloadFileFunc(items.sealedFileId)">
											<div>
												<img src="../assets/icon_gaizhang@2x.png" alt="" />
											</div>
											<div>
												<span>盖章版</span>
											</div>
										</div>
									</div>
									<span slot="reference">{{ items.name }}</span>
								</el-popover>
							</div>
						</div>
					</div>
				</div>
			</template>
			<template v-if="!scrollLoading && !fundScrollData.length">
				<el-empty :image-size="200"></el-empty>
			</template>

			<p v-if="page.total > fundScrollData.length || scrollLoading" class="jiazaiya queueLoading">
				<i class="el-icon-loading"></i> 正在加载数据，请耐心等待...
			</p>

			<p v-if="scrollNoMore && fundScrollData.length && page.total === fundScrollData.length && !scrollLoading" class="jiazaiya queueNoMore">
				没有更多了
			</p>

			<transition name="el-fade-in">
				<div class="toTop" v-if="topComShow" @click="toTopFunc()">
					<div class="fanzhuan">
						<i class="el-icon-download" />
					</div>
				</div>
			</transition>
		</div>
	</div>
</template>
<script>
import { fundTypeNum } from '@/api/productApi/integratedQuery'
import { exportFundData } from '@/api/graphQl/fundDataExport'
import { getEnum, downloadFile, jsonArray } from '@/api/productApi/file'
import { graphQlParams } from './graphQlParams'
import { SpecialReplace } from '@/utils/characters'
import { debounce } from '@/utils/debounce'
import { RoleVisible } from '@/api/productApi/rolesSetting'
import { timerConversionStr } from '@/filters'
export default {
	name: 'FundList',

	components: {},

	data() {
		return {
			form: {
				statusList: [],
				fundLike: '',
				status: '',
				selectType: 'list',
				fundType: '',
				fundRaiseType: '',
				manageStatus: '0'
			},
			enumData: {},
			fundScrollData: [],
			fundTypeList: [],
			fundOperationStatus: [],
			scrollNoMore: false,
			scrollLoading: false,
			page: {
				size: 10,
				num: 1
			},
			SpecialReplace,
			topComShow: false,
			scrollTopY: 0,
			timeDistance: 0, // 记录距离顶部的量
			cacheLastTime: 0, // 缓存上一次的量
            authFileList: []
		}
	},

	async mounted() {
        await this.fileInfoAuth()
		await this.getProductDictList()
		this.getListItem()
		this.getFundNum()
		this.scrollEventFunc()
		this.windowScroll()
		this.$nextTick(() => {
			this.setDom()
		})
	},

	methods: {
        async fileInfoAuth() {
            await RoleVisible().then(res => {
                if (res.msgCode === 'Y') {
                    const parNode = res.data.body.filter(item => item.fieldCode === 'fundFileInfo')
                    const list = res.data.body.filter(item => item.fieldCode !== 'updateFile' && parNode.some(items => items.fieldId === item.parentId))
                    this.authFileList = list
                }
            })
        },

		windowScroll() {
			document.getElementsByClassName('IntegratedQuery')[0].addEventListener(
				'scroll',
				() => {
					setTimeout(() => {
						this.timeDistance = document.getElementsByClassName('IntegratedQuery')[0].scrollTop
						const searchHeight = document.getElementsByClassName('sousuotiaojian')[0]
						const childrenItem = document.getElementsByClassName('listItemClass')[0]
						if (Math.abs(this.timeDistance - this.cacheLastTime) > searchHeight.getClientRects()[0].height) {
							const top = this.timeDistance - this.cacheLastTime
							if (top > 0) {
								searchHeight.setAttribute('style', `width:${childrenItem.getClientRects()[0].width}px;top:-${top - 45}px;`)
							} else if (top < 0) {
								searchHeight.setAttribute('style', `width:${childrenItem.getClientRects()[0].width}px;top:45px;`)
								childrenItem.setAttribute('style', `margin-top:${searchHeight.getClientRects()[0].height + 8}px;`)
							}
							this.cacheLastTime = this.timeDistance
						}
					})
					// 判读回到顶部组件是否显隐
					const obj = document.getElementsByClassName('FundList')[0].getClientRects()[0]
					if (obj.top < -140) {
						this.topComShow = true
					} else {
						this.topComShow = false
					}
				},
				true
			)
		},

		// 滚动加载数据方法
		toTopFunc() {
			document.getElementsByClassName('IntegratedQuery')[0].scroll({ top: 0, behavior: 'smooth' })
		},

		scrollEventFunc() {
			document.getElementsByClassName('IntegratedQuery')[0].addEventListener(
				'scroll',
				debounce(() => {
					const num = document.getElementsByClassName('IntegratedQuery')[0].scrollTop
					if (this.page.total !== this.fundScrollData.length) {
						if (num - this.scrollTopY > 900) {
							this.scrollTopY = num
							this.page.num += 1
							this.getListItem(1)
						}
					} else {
						this.scrollLoading = false
						this.scrollNoMore = true
					}
				}, 500),
				true
			)
		},

		// 获取数据
		getListItem(num) {
			if (SpecialReplace(this.form.fundLike, false)) {
				return
			}
			this.form.graphQlParams = graphQlParams
			// 当切换类型时先清空数据
			if (!num) {
				this.resetForm()
			}
			const form = { ...jsonArray(this.form) }
			if (!form.statusList.length) {
				this.fundOperationStatus.forEach(item => {
					form.statusList.push(item.typeCode)
				})
			}
			this.scrollLoading = true
			exportFundData(form, JSON.stringify(this.page).replace(/"/g, ''))
				.then(res => {
					if (res.data.getFundDetailInfoV1) {
						res.data.getFundDetailInfoV1.fundDetailGraphqlDTOs.forEach(item => {
							if (item && item.baseInfo) {
								if (item.baseInfo.fundType) {
									const obj = this.fundTypeList.find(items => items.typeCode === item.baseInfo.fundType)
									// 基金类型
									item.fundType = obj ? obj.typeName : ''
								}
								// 基金全称
								item.fundFullName = item.baseInfo.fundFullName
								// 基金代码
								item.fundCode = item.baseInfo.fundCode
								// 下属基金
								item.branchShareList = item.baseInfo.branchShareList ? item.baseInfo.branchShareList : []
								item.isSingleShare = item.baseInfo.isSingleShare
							}
							if (item && item.dateInfo) {
								// 合同生效日/产品成立日
								item.establishDate = item.dateInfo.establishDate
							}
							if (item && item.organInfo) {
								// 托管机构
								item.trusteeFullName = item.organInfo.trusteeFullName
							}
							// 运行状态
							item.statusMsg = this.fundOperationStatus.find(items => items.typeCode === item.status)
								? this.fundOperationStatus.find(items => items.typeCode === item.status).typeName
								: ''
							if (item && item.fundManagerInfoList && item.fundManagerInfoList.length) {
								// 经理
								const manNameList = []
								item.fundManagerInfoList.forEach(items => {
                                    if (!items.endDate || new Date(timerConversionStr(items.endDate)) > new Date()) {
                                        manNameList.push(items.managerName)
                                    }
								})
								item.managerNames = [...new Set(manNameList)].join(',')
							}
							if (item && item.fundFileInfo) {
								item.fileList = []
								if (item.fundRaiseType === '1') {
									// 公募文件列表
									const list = [
										{ key: 'fundContractId2', value: '基金合同' },
										{ key: 'trustAgreementId2', value: '托管协议' },
										{ key: 'enlistExplainId2', value: '招募说明书' },
										{ key: 'productDataResume', value: '产品资料概要' },
										{ key: 'raiseLogonReplyId', value: '募集注册批复' }
									]
									list.forEach(items => {
										if (item.fundFileInfo[items.key] && this.authFileList.some(val => val.fieldCode === items.key)) {
											if (
												item.fundFileInfo[items.key].sealedFileId ||
												item.fundFileInfo[items.key].firstFileId ||
												item.fundFileInfo[items.key].finalFileId
											) {
												const obj = {
													name: items.value,
													sealedFileId: item.fundFileInfo[items.key].sealedFileId,
													firstFileId: item.fundFileInfo[items.key].firstFileId,
													finalFileId: item.fundFileInfo[items.key].finalFileId
												}
												item.fileList.push(obj)
											}
										}
									})
								} else if (item.fundRaiseType === '2') {
									// 专户文件列表
									const list = [
										{ key: 'capitalManageContractId', value: '资产管理合同' },
										{ key: 'planExplainId', value: '计划说明书' },
										{ key: 'riskProclaimId', value: '风险揭示书' },
										{ key: 'filingLetterId', value: '协会备案函' }
									]
									list.forEach(items => {
										if (item.fundFileInfo[items.key] && this.authFileList.some(val => val.fieldCode === items.key)) {
											if (
												item.fundFileInfo[items.key].sealedFileId ||
												item.fundFileInfo[items.key].firstFileId ||
												item.fundFileInfo[items.key].finalFileId
											) {
												const obj = {
													name: items.value,
													sealedFileId: item.fundFileInfo[items.key].sealedFileId,
													firstFileId: item.fundFileInfo[items.key].firstFileId,
													finalFileId: item.fundFileInfo[items.key].finalFileId
												}
												item.fileList.push(obj)
											}
										}
									})
								}
							} else {
								item.fileList = []
							}
						})
						this.page.total = res.data.getFundDetailInfoV1.total
						this.fundScrollData = [...this.fundScrollData, ...res.data.getFundDetailInfoV1.fundDetailGraphqlDTOs]
						if (this.page.total === this.fundScrollData.length) {
							this.scrollNoMore = true
						}
						if (!num) {
							this.setDom()
						}
					}
				})
				.finally(() => {
					this.scrollLoading = false
				})
		},

		// 文件下载
		downloadFileFunc(id) {
			if (!id) {
				return false
			}
			downloadFile({ fid: id }).then(item => {
				if (item.msgCode === 'N') {
					this.$message({ showClose: true, message: '文件不存在', type: 'error' })
					return
				}
				if (item) {
					this.$message({
						showClose: true,
						message: '正在下载，请稍等......',
						type: 'success'
					})
					window.open(`/update/download.do?fid=${id}`)
				}
			})
		},

		resetForm() {
			this.scrollTopY = 0
			this.page.num = 1
			this.fundScrollData = []
		},

		// 跳转到基金详情
		itemClick(obj) {
			if (obj.fundSysCode && obj.fundRaiseType) {
				window.open(`/web/product/integratedQuery/fundInfo?fundSysCode=${obj.fundSysCode}&fundRaiseType=${obj.fundRaiseType}`, '_blank')
			} else {
				this.$message({ type: 'error', message: `必要参数fundSysCode，fundRaiseType缺失` })
			}
		},

		// 切换查询条件
		handleClick(tab, num) {
			if (num) {
				if (tab.fundTypeCode) {
					// 切换基金类型
					if (tab.fundTypeCode === this.form.fundType) {
						this.form.fundType = ''
					} else {
						this.form.fundType = tab.fundTypeCode
					}
				} else {
					// 切换产品类型
					this.form.fundRaiseType = tab.fundRaiseType
					this.form.fundType = ''
				}
			}
			this.getFundNum()
			this.getListItem()
		},

		// 切换运作状态
		btnClick(property) {
			if (property) {
				if (this.form.statusList.includes(property)) {
					this.form.statusList = this.form.statusList.filter(item => item !== property)
				} else {
					this.form.statusList.push(property)
				}
			} else {
				this.form.statusList = []
			}
			this.getListItem()
		},

		// 获取计数
		async getFundNum() {
			await fundTypeNum({ fundRaiseType: this.form.fundRaiseType }).then(res => {
				if (res.msgCode === 'Y') {
					res.data.body.forEach(item => {
						if (!item.fundTypeCode && !item.fundRaiseType) {
							item.fundRaiseType = ''
						}
					})
					this.$set(
						this.enumData,
						'prodType',
						res.data.body.filter(item => !item.fundTypeCode)
					)
					this.$set(
						this.enumData,
						'fundType',
						res.data.body.filter(item => item.fundTypeCode)
					)
					this.setDom()
				}
			})
		},

		// 获取枚举
		async getProductDictList() {
			await getEnum(['fundType', 'fundOperationStatus']).then(res => {
				if (res.msgCode === 'Y') {
					this.fundTypeList = res.data.body.fundType
					this.fundOperationStatus = res.data.body.fundOperationStatus
				}
			})
		},

		setDom() {
			setTimeout(() => {
				const parNode = document.getElementsByClassName('FundList')[0].getClientRects()[0].width
				const childrenSeach = document.getElementsByClassName('sousuotiaojian')[0]
				const childrenItem = document.getElementsByClassName('listItemClass')[0]
				const queueLoading = document.getElementsByClassName('queueLoading')[0]
				const queueNoMore = document.getElementsByClassName('queueNoMore')[0]
				childrenSeach.setAttribute('style', `width:${parNode}px;`)
				if (queueLoading) {
					queueLoading.setAttribute('style', `width:${parNode}px;`)
				}
				if (queueNoMore) {
					queueNoMore.setAttribute('style', `width:${parNode}px;`)
				}
				childrenItem.setAttribute(
					'style',
					`margin-top:${document.getElementsByClassName('sousuotiaojian')[0].getClientRects()[0].height + 8}px;`
				)
			})
		}
	}
}
</script>
<style lang="scss" scoped src='./index.scss'>
</style>
